<template>
  <div class="main-container">
    <div class="main-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{path: '/course/course'}">课程内容管理</el-breadcrumb-item>
        <el-breadcrumb-item>新增课程</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="wrap">
      <div class="content">
        <el-form class="mt-30" ref="form" :model="form" label-width="150px" style="width: 800px;">
          <div style="width: 450px">
            <el-form-item label="课程标题" prop="courseTitle" :rules="[ { required: true, message: '标题不能为空'}]">
              <el-input v-model="form.courseTitle"></el-input>
            </el-form-item>
            <el-form-item label="pc课程封面图" prop="courseTitleImage">
              <el-upload
                class="avatar-uploader"
                :action="actionUrl + '?fileType=2&businessType=3'"
                :show-file-list="false"
                :on-success="courseImageSuccess"
                :file-list="imageList"
                >
                <img v-if="form.courseTitleImage" :src="form.courseTitleImage" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              
            </el-form-item>
            <el-form-item prop="memo" style="width:700px">
              <span style="color:red">* 建议上传图片尺寸：230 * 140（可以倍数增大）
                <br/>&nbsp;&nbsp;内容放在中间区域，上下左右预留背景，防止鼠标滑过图片放大时边上内容被遮挡</span>
            </el-form-item>
            <el-form-item label="手机课程封面图" prop="courseTitlePhoneImage">
              <el-upload
                class="avatar-uploader"
                :action="actionUrl + '?fileType=2&businessType=3'"
                :show-file-list="false"
                :on-success="coursePhoneImageSuccess"
                :file-list="phoneImageList"
                >
                <img v-if="form.courseTitlePhoneImage" :src="form.courseTitlePhoneImage" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <span style="color:red;white-space: nowrap;">* 建议上传图片尺寸：240 * 180（可以倍数增大）<br/>&nbsp;&nbsp;内容放在中间区域，上下左右预留背景</span>
            </el-form-item>
            <el-form-item label="课程类型" prop="contentType" :rules="[ { required: true, message: '请选择课程类型'}]">
              <el-select v-model="form.contentType" style="width: 100%">
                <el-option :value="1" label="图文课程"></el-option>
                <el-option :value="2" label="视频课程"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上传视频" v-if="form.contentType == 2" prop="videoLink">
              <el-upload
               
                :action="actionUrl + '?fileType=3&businessType=3'"
                :on-success="videoSuccess"
                :file-list="videoList"
                :limit="1"
                :on-remove="videoHandleRemove"
                >
                <el-button size="small" type="primary">点击上传</el-button>
                <span>如需替换文件,先删除</span>
              </el-upload>
            </el-form-item>
            <el-form-item label="上传pdf">
              <el-upload
                :action="actionUrl + '?fileType=1&businessType=3'"
                :file-list="pdfList"
                :on-success="uploadPdfSuccess"
                :on-error="uploadError"
                :limit="1"
                :on-remove="pdfhandleRemove"
                >
                <el-button size="small" type="primary">点击上传</el-button>
                <span>如需替换文件,先删除</span>
              </el-upload>
            </el-form-item>
            <transition name="el-zoom-in-top">
              <el-form-item label="课程分类" v-if="form.contentType!=3" :rules="[ { required: true, message: '课程分类不能为空'}]">
                <el-cascader
                  :options="data"
                  @active-item-change="handleItemChange"
                  :props="props"
                  @change="changeCourseType"
                ></el-cascader>
              </el-form-item>
            </transition>
            <el-form-item label="排序" prop="sort">
              <div class="help-tip el-iconhelp_tip element-icons" style="left: -62px;">
                <p class="help-tip-content">页面中可以通过“排序”进行倒序排序。</p>
              </div>
              <el-input-number v-model="form.sort" :min="0" :controls="false"></el-input-number>
            </el-form-item>
            <el-form-item label="课程描述" prop="description">
              <el-input v-model="form.description" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="关键字" prop="seoKeyword">
              <el-input v-model="form.seoKeyword" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="memo">
              <el-input v-model="form.memo" type="textarea"></el-input>
            </el-form-item>
          </div>
          <el-form-item label="课程内容" style="height:400px">
            <quill-editor 
              ref="myTextEditor"
              v-model="content"
              :options="editorOption"
              @change="onEditorChange($event)"
              style="height:300px">
            </quill-editor>
          </el-form-item>
          <!-- <el-form-item label="pdf转图片" style="height:400px">
            <quill-editor 
              ref="myPdfToPageEditor"
              v-model="pdfToPage"
              :options="editorOption"
              @change="onPdfToPageChange($event)"
              style="height:300px">
            </quill-editor>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-upload
      :action="actionUrl + '?fileType=2&businessType=3'"
      :on-success="quillSuccess"
      style="display:none"
      >
      <el-button type="primary" id="uploadHidden">点击上传</el-button>
    </el-upload>

    <!-- <el-upload
      :action="actionUrl + '?fileType=2&businessType=3'"
      :on-success="pdfToPageQuillSuccess"
      style="display:none"
      >
      <el-button type="primary" id="pdfToPageUploadHidden">点击上传</el-button>
    </el-upload> -->
  </div>
</template>

<script>
  import {quillEditor} from 'vue-quill-editor'
  import 'quill/dist/quill.snow.css'
  import oss from '@/libs/aliOss'
  // 富文本提示
  import { addQuillTitle } from '@/libs/quill-title.js'
  export default {
    components: {
      quillEditor
    },
    data () {
      return {
        form: {
          courseTitleImage: '',
          courseTitlePhoneImage: '',
          pdfUrl: '',
          videoLink: '',
          courseTitle: '',
          contentType: '',
          courseTypeId: '',
          sort: '',
          description: '',
          memo: '',
        },
        imageList: [],
        phoneImageList: [],
        videoList: [],
        pdfList: [],
        content: '',
        pdfToPage: '',
        courseType: '',
        treeData: [],
        actionUrl: '',
        data: [],
        props: {
          value: 'courseTypeId',
          label: 'courseName',
          children: 'children'
        },
        editorOption: {
          modules: {
           toolbar: [
              ['bold', 'italic', 'underline', 'strike'],
              ['blockquote', 'code-block'],
              [{ 'header': 1 }, { 'header': 2 }],
              [{ 'list': 'ordered' }, { 'list': 'bullet' }],
              [{ 'script': 'sub' }, { 'script': 'super' }],
              [{ 'indent': '-1' }, { 'indent': '+1' }],
              [{ 'direction': 'rtl' }],
              [{ 'size': ['small', false, 'large', 'huge'] }],
              [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
              [{ 'font': [] }],
              [{ 'color': [] }, { 'background': [] }],
              [{ 'align': [] }],
              ['clean'],
              ['link', 'image', 'video']
            ]
          }
        },
        
        pdfHeaders: {
          'Content-Type': 'multipart/form-data'
        }
      }
    },
    activated() {
      this.actionUrl = this.$api.upload()
      this.$refs.form.resetFields()
      this.loadCourseType()
      this.getSort()
    },
    created() {
      this.actionUrl = this.$api.upload()
      this.loadCourseType()
      this.getSort()
    }, 
    mounted() {
      addQuillTitle();
      this.$refs.myTextEditor.quill.getModule('toolbar').addHandler('image', this.imgHandler);
      
      // this.$refs.myPdfToPageEditor.quill.getModule('toolbar').addHandler('image', this.pdfToPageHandler);
    },
    methods: {
      imgHandler(state){
        this.addRange = this.$refs.myTextEditor.quill.getSelection()
        if (state) {
          let fileInput = document.getElementById('uploadHidden')
          fileInput.click(); // 加一个触发事件
        }
      },
      // pdfToPageHandler(state){
      //   this.pdfToPageRange = this.$refs.myPdfToPageEditor.quill.getSelection()
      //   if (state) {
      //     let fileInput = document.getElementById('pdfToPageUploadHidden')
      //     fileInput.click(); // 加一个触发事件
      //   }
      // },
      loadCourseType() {
        this.$api.courseType.getList({documentType: 1, courseLevel: 1}).then(res => {
          if(res.success){
            res.data.forEach(el => {
              el.children = []
            })
            this.data = res.data;
          }
        })
      },
      getSort(){
        var documentType = 1;
        this.$api.course.getSort(documentType).then(res => {
            if(res.success){
              this.form.sort = res.data
            }
        })
      },
      onSubmit() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.$api.course.add(this.form).then(res => {
              if(res.success) {
                this.$message.success('保存成功')
                this.videoList = []
                this.pdfList = []
                this.$refs.form.resetFields()
                this.$router.push('/course/course');
              }
            })
          }
        })
      },
      uploadCourseBefore(file){
        let fd = new FormData()
        fd.append('Filedata', file)
        this.$api.upload(fd).then(res => {
          if(res.success){
            this.$message.success('上传成功')
            this.form.courseTitleImage = res.data.totalUrl
          }
          return false
        })
      },
      handleItemChange(val){
        this.data.forEach(item => {
          console.log(item.children)
          if(item.children.length <= 0){
            if(item.courseTypeId == val){
              this.$api.courseType.getChildren(item.courseCode).then(res => {
                item.children = res.data
              })
            }
          }
        })
      },
      uploadPdfSuccess(res, file){
        if(res.success){
          this.form.pdfUrl = res.data.totalUrl
        } else {
          this.pdfList = []
        }
      },
      uploadError(err){
        this.$message.error(err)
      },
      pdfhandleRemove(file, fileList) {
        this.form.pdfUrl = ''
      },
      videoHandleRemove(file, fileList){
        this.form.videoLink = ''
      },
      
      onReset() {
        this.$refs.form.resetFields()
      },
      onEditorChange(editor) {
        this.form.content = this.content
        // console.log('editor blur!', editor)
      },
      // onPdfToPageChange(editor){
      //   this.form.pdfToPage = this.pdfToPage
      // },
      changeCourseType(val) {
        console.log(val)
        this.form.courseTypeId = val[1]
      },
      courseImageSuccess(res, file) {
        this.form.courseTitleImage = res.data.totalUrl
        this.$forceUpdate()
        // this.imageUrl = URL.createObjectURL(file.raw);
      },
      coursePhoneImageSuccess(res, file){
        this.form.courseTitlePhoneImage = res.data.totalUrl
        this.$forceUpdate()
      },
      videoSuccess(res, file) {
        if(res.success) {
          this.form.videoLink = res.data.totalUrl
        } else {
          this.videoList = []
        }
      },
      quillSuccess(res, file, fileList){
        this.$message.success('上传成功');
        const imgUrl = res.data.totalUrl;
        this.$refs.myTextEditor.quill.insertEmbed(this.addRange != null ? this.addRange.index : 0, 'image', imgUrl)
      },
      // pdfToPageQuillSuccess(res, file, fileList){
      //   this.$message.success('上传成功');
      //   const imgUrl = res.data.totalUrl;
      //   this.$refs.myPdfToPageEditor.quill.insertEmbed(this.pdfToPageRange != null ? this.pdfToPageRange.index : 0, 'image', imgUrl)
      // },
      fnUploadRequest(option){
        oss.ossUploadFile(option)
      }
    }
  }
</script>
